<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="account">
      <el-input v-model="loginForm.account" :placeholder="$t('message.account.accountPlaceholder1')">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        :placeholder="$t('message.account.accountPlaceholder2')"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <el-form-item v-show="captchaEnabled" prop="captchaCode">
    <el-col :span="15">
      <el-input
        text
        maxlength="4"
        :placeholder="$t('message.account.accountPlaceholder3')"
        v-model="loginForm.captchaCode"
        clearable
        autocomplete="off"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><Position /></el-icon>
        </template>
      </el-input>
    </el-col>
    <el-col :span="1"></el-col>
    <el-col :span="8">
      <div class="login-content-code">
        <img
          class="login-content-code-img"
          @click="getCaptcha"
          width="130px"
          height="38px"
          :src="captchaImage"
          style="cursor: pointer"
        />
      </div>
    </el-col>
  </el-form-item>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { ElMessage, ElNotification } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled, Position } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
//import md5 from "md5";
import authApi from "@/api-services/apis/system/authApi";
import { SysAuth } from "@/api-services/models/system";
import { feature } from "@/utils/axios-utils";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const captchaEnabled = ref(false);
const captchaImage = ref("");
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<SysAuth.LoginInput>({
  account: "",
  password: "",
  captchaCode: "",
  captchaCodeId: ""
});

const getCaptcha = async () => {
  if (!captchaEnabled.value) {
    return;
  }
  const res = await authApi.getCaptcha();
  captchaImage.value = res.data.data?.img;
  loginForm.captchaCodeId = res.data.data?.codeId;
};

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const [err, res] = await feature(authApi.login(loginForm));
      if (err) {
        ElMessage.error(err.message);
        getCaptcha(); // 重新获取验证码
        return;
      }

      await userStore.getUserInfo();
      userStore.setToken(res.data.data?.accessToken);

      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 GoodAdmin",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(async () => {
  const config = await authApi.getConfig();
  captchaEnabled.value = config.data.data?.isCaptcha ?? false;
  await getCaptcha();

  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
